const express = require('express')
const bodyParser = require('body-parser')
const mysql = require('mysql')
const axios = require('axios')

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'ok',
    database: 'myapp'
})

const app = express()

// 接受POST请求
app.use(bodyParser.json())
app.use(express.urlencoded({ extended: true }))

// 登录操作
app.post('/zhlogin', (req, res) => {
    console.log('账户密码登录')
    // 获取
    const {username,password,openid}=req.body
    // 登陆
    connection.query('select * from`users`where username=? and password=?',[username,password],(err,results)=>{
        if (results.length) {
            const uid=results[0].id
            connection.query('update `users`set `wxcode`=?where `id`=?',[openid,uid],(err,results)=>{
                if (results.affectedRows) {
                    res.json({
                        code:1,
                        msg:'登陆成功',
                        user:results[0]
                    })
                } else {
                    res.json({
                        code:-1,
                        msg:'绑定失败',
                        openid:openid
                    }) 
                }
            })
        } else {
            console.log('登陆失败')
        }
    })
    console.log(username,password,openid)
})

app.post('/wxlogin', (req, res) => {
    const code = req.body.code
    axios.get('https://api.weixin.qq.com/sns/jscode2session?appid=wx914bdd07703d939b&secret=340c8309c7df0f0ef66be42fc6473c99&js_code=' + code + '&grant_type=authorization_code')
        .then(res => {
            console.log(res.data)
            const openid=res.data.openid
            connection.query('select * from`users`where wxcode=?',openid,(err,results)=>{
                console.log(results.length)
                if (results.length) {//openID如果存在，当前登陆的微信和账户绑定过
                    res.json({
                        code:1,
                        msg:'登陆成功',
                        user:res[0]
                    })
                } else {//不存在，当前登陆的微信没有和账户绑定
                    res.json({
                    code:-1,
                    msg:'没有绑定账户',
                    openid:openid
                })
                }
            })
            // 获取openID(微信账号唯一标志)
            // 查询openID在数据库中是否存在
            // 如果存在就查询用户信息
            // 如果不存在就让用户登录并绑定openID

        })
})

app.listen(3000)